import ujson
import pandas
import os


def read_strategies_map(fabfilepath):
  lines = open(fabfilepath).readlines()
  strat_map_cnt = 0
  stratlines = []

  for line in lines:
    if line.startswith("strategies_map"):
      strat_map_cnt += 1
      if strat_map_cnt > 1:
        break
    if strat_map_cnt == 1:
      stratlines.append(line)

  exec("".join(stratlines))
  return locals()['strategies_map']


def get_strat_cmds(root_path, strat_row, tdstr):
  lines = open(os.path.join(root_path, strat_row['binary'])).readlines()
  config_dir = [line for line in lines if line.find("CONFIG_DIR=") >= 0]
  config_dict = {"COIN_DEPLOY_DIR": ""}
  if len(config_dir) > 0:
    assert len(config_dir) == 1
    config_dir = config_dir[0][config_dir[0].find("/") + 1:].replace('"', '').strip()
    config_dict["CONFIG_DIR"] = config_dir
    # print(config_dict)
  else:
    config_dir = ""

  lines = [
      line.strip().replace("&", "").replace('"', '').split("filename")[-1].replace(
          '$', '%').replace("{", "(").replace("}", ")s").strip() % config_dict
      for line in lines
      if line.find("config_filename") >= 0
  ]

  confs = []
  for line in lines:
    conf = ujson.loads(open("coin_deploy/" + line).read())
    for product in conf['products'].keys():
      confdict = conf['common']['trade_subreq'].copy()
      confdict['product'] = product
      confs.append(confdict)
  # print(lines)
  confdf = pandas.DataFrame(confs)
  confdf['host'] = strat_row['host']

  print(confdf)

  cmds = []

  for _, confrow in confdf.iterrows():
    cmd = ("./pyrunner coin/strategy/mm/tool/taker_ratio.py "
           + "--out_dir=oe_stat_frtr/%s " % confrow['exchange']
           + "--root_dir=/remote/iosg/strat-1/buckets/log.raw.coin/live/og_proto_log "
           + "--exchange=%s " % confrow['exchange'] + "--market_type=%s " % confrow['market_type']
           + "--trading_date=%s " % tdstr + "--machine=%s " % confrow['host']
           + "--symbol=%s " % confrow['product'])
    cmds.append(cmd)

  for groupconf, _ in confdf.groupby(['exchange', 'market_type', 'host']):
    cmd = ("./pyrunner coin/strategy/mm/tool/fr_analysis.py "
           + "--out_dir=oe_stat_frtr/%s " % confrow['exchange']
           + "--root_dir=/remote/iosg/strat-1/buckets/log.raw.coin/live/og_proto_log "
           + "--exchange=%s " % confrow['exchange'] + "--market_type=%s " % confrow['market_type']
           + "--machine=%s " % confrow['host'] + "--trading_date=%s " % tdstr)
    cmds.append(cmd)
  return cmds


tdstr = "20190628-20190701"

strat_map = read_strategies_map("coin_deploy/hk_lm_agg/fabfile.py")
strat_df = pandas.DataFrame(strat_map)
cmds = []
for _, strat_row in strat_df.iterrows():
  cmds.extend(get_strat_cmds("coin_deploy/hk_lm_agg", strat_row, tdstr))

print("-" * 20)

for cmd in cmds:
  print(cmd)
  res = os.system(cmd)
  if res == 256:
    break
